package com.copyctrl.campus.portal.controller;

import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.HttpConstant;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.common.constant.Status;
import com.copyctrl.campus.common.domain.ScrollResult;
import com.copyctrl.campus.common.domain.User;
import com.copyctrl.campus.common.exception.DataBaseException;
import com.copyctrl.campus.common.model.ApiResponse;
import com.copyctrl.campus.portal.dto.DynamicDTO;
import com.copyctrl.campus.portal.service.DynamicService;
import com.copyctrl.model.CampDynamic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author:JH
 * @version:1.0
 */
@RestController
@RequestMapping("/dynamic")
public class DynamicController {
    @Autowired
    DynamicService dynamicService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping
    public ApiResponse add(@RequestBody String dynamic, HttpServletRequest request) {
        Map map = JSONUtil.toBean(dynamic, Map.class);
        CampDynamic bean = JSONUtil.toBean(map.get("dynamic").toString(), CampDynamic.class);
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取openid,转换成id存入redis中
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        bean.setUserId(user.getId());
        int i = dynamicService.addDynamic(bean);
        if (i == 0) {
            throw new DataBaseException(Status.UNKNOWN_ERROR);
        }
        return ApiResponse.ofSuccess("ok");
    }

    @DeleteMapping("/{id}")
    public ApiResponse deleteDynamic(@PathVariable Integer id) {
        int i = dynamicService.deleteDynamic(id);
        if (i == 0) {
            throw new DataBaseException(Status.UNKNOWN_ERROR);
        }
        return ApiResponse.ofSuccess("ok");
    }

    @PutMapping
    public ApiResponse updateDynamic(@RequestBody String dynamic,HttpServletRequest request) {
        Map map = JSONUtil.toBean(dynamic, Map.class);
        CampDynamic bean = JSONUtil.toBean(map.get("dynamic").toString(), CampDynamic.class);
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取User，再从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        bean.setUserId(user.getId());
        int i = dynamicService.updateDynamic(bean);
        if (i == 0) {
            throw new DataBaseException(Status.UNKNOWN_ERROR);
        }
        return ApiResponse.ofSuccess("ok");
    }

    /**
     * 获取某人的所有动态
     * @param id
     * @param offset
     * @param max
     * @param userid 查找的用户id(用于获取点赞列表)
     * @return
     */
    @GetMapping("/{userid}/{offset}/{max}/{finduserid}")
    public ApiResponse getSelf(@PathVariable("userid") Integer id, @PathVariable Integer offset, @PathVariable Long max,@PathVariable("finduserid") Integer userid) {
        ScrollResult<DynamicDTO> dynamics = dynamicService.getDynamics(id, offset, max,userid);
        return ApiResponse.ofSuccess(dynamics);
    }

    //
    @GetMapping("/all/{offset}/{max}")
    public ApiResponse getAll(HttpServletRequest request, @PathVariable Integer offset, @PathVariable Long max) {
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取User，再从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        ScrollResult<DynamicDTO> allDynamics = dynamicService.getAllDynamics(user.getId(), offset, max);
        return ApiResponse.ofSuccess(allDynamics);
    }


    /**
     * 点赞
     * @param dynamicId
     * @param request
     * @return
     */
    @PostMapping("/dianzan/{dynamicId}")
    public ApiResponse dianzan(@PathVariable String dynamicId, HttpServletRequest request) {
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取User，再从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        Long liked = dynamicService.liked(user.getId().toString(), dynamicId);
        return liked==1? ApiResponse.ofSuccess("ok"):ApiResponse.ofFailure("服务错误啦");
    }

    @PostMapping("/cancel/{dynamicId}")
    public ApiResponse cancelZan(@PathVariable String dynamicId, HttpServletRequest request) {
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取User，再从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        Long liked = dynamicService.cancel(user.getId().toString(), dynamicId);
        return liked==1? ApiResponse.ofSuccess("ok"):ApiResponse.ofFailure("服务错误啦");
    }

    @GetMapping("/likes/{dynamicId}")
    public ApiResponse getLikes(@PathVariable String dynamicId) {
        String json = redisTemplate.opsForValue().get(RedisConstant.DYNAMIC_KEY + dynamicId);
        CampDynamic dynamic = JSONUtil.toBean(json, CampDynamic.class);
        return ApiResponse.ofSuccess(dynamic.getLikes());
    }
}
